package cn.dgiot.fd.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.oss.common.utils.StringUtils;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.CreateConsumerGroupRequest;
import com.aliyuncs.iot.model.v20180120.CreateConsumerGroupResponse;
import com.aliyuncs.iot.model.v20180120.CreateConsumerGroupSubscribeRelationResponse;
import com.aliyuncs.iot.model.v20180120.CreateProductTopicRequest;
import com.aliyuncs.iot.model.v20180120.CreateProductTopicResponse;
import com.aliyuncs.iot.model.v20180120.CreateSubscribeRelationRequest;
import com.aliyuncs.iot.model.v20180120.CreateSubscribeRelationResponse;
import com.aliyuncs.iot.model.v20180120.DeleteConsumerGroupRequest;
import com.aliyuncs.iot.model.v20180120.DeleteConsumerGroupResponse;
import com.aliyuncs.iot.model.v20180120.QueryConsumerGroupByGroupIdRequest;
import com.aliyuncs.iot.model.v20180120.QueryConsumerGroupByGroupIdResponse;
import com.aliyuncs.iot.model.v20180120.QueryProductTopicRequest;
import com.aliyuncs.iot.model.v20180120.QueryProductTopicResponse;
import com.aliyuncs.iot.model.v20180120.QueryProductTopicResponse.ProductTopicInfo;
import com.aliyuncs.iot.model.v20180120.QuerySubscribeRelationRequest;
import com.aliyuncs.iot.model.v20180120.QuerySubscribeRelationResponse;
import com.aliyuncs.iot.model.v20180120.UpdateConsumerGroupResponse;
import com.aliyuncs.iot.model.v20180120.UpdateSubscribeRelationRequest;
import com.aliyuncs.iot.model.v20180120.UpdateSubscribeRelationResponse;

import cn.dgiot.fd.contant.AliyunConfig;
import cn.dgiot.fd.contant.MessageConfig;
import cn.dgiot.fd.model.DictionarieModel;
import cn.dgiot.fd.model.MessageModel;
import cn.dgiot.fd.service.IDictionarieService;
import cn.dgiot.fd.service.IMessageService;

/**
 * [消息相关]
 * @author
 *
 */
@Service
public class MessageServiceImpl extends BaseServiceImpl implements IMessageService{
	
 
	private Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);

	@Autowired
	private AliyunConfig aliyunConfig;
	@Autowired
	private MessageConfig messageConfig;
	 
	@Autowired
	private IDictionarieService dictionarieService;
	
	@Override
	public void messageInit() {
		/** 查询字典表 */
		DictionarieModel param = new DictionarieModel();
		param.setDictionarieKey("groupId");
		param.setDictionarieType("MessageConsumer");
		DictionarieModel dictionarieModel = dictionarieService.getDictionarie(param);
		String groupId = "";
		/** 判断消息消费组字典项是否存在 */
		if(dictionarieModel != null) {
			/** 消费组id */
			groupId = dictionarieModel.getDictionarieValue();
			/** 调用接口判断消费组是否存在 */
			MessageModel messageModel = new MessageModel();
			messageModel.setGroupId(groupId);
			QueryConsumerGroupByGroupIdResponse queryConsumerGroupByGroupIdResponse = queryConsumerGroupByGroupId(messageModel);
			if(!queryConsumerGroupByGroupIdResponse.getSuccess()) {
				CreateConsumerGroupResponse createConsumerGroupResponse = createConsumerGroup();
				if(createConsumerGroupResponse != null && createConsumerGroupResponse.getSuccess()) {
					groupId = createConsumerGroupResponse.getGroupId();
					DictionarieModel updateParam = new DictionarieModel();
					updateParam.setDictionarieKey("groupId");
					updateParam.setDictionarieValue(groupId);
					updateParam.setDictionarieType("MessageConsumer");
					updateParam.setDictionarieDescribe("消息消费组id");
					dictionarieService.updateDictionarie(dictionarieModel);
				}
			}
			 
		}else {
			CreateConsumerGroupResponse createConsumerGroupResponse = createConsumerGroup();
			if(createConsumerGroupResponse != null && createConsumerGroupResponse.getSuccess()) {
				groupId = createConsumerGroupResponse.getGroupId();
				DictionarieModel insertParam = new DictionarieModel();
				insertParam.setId(UUID.randomUUID().toString().replace("-", ""));
				insertParam.setDictionarieKey("groupId");
				insertParam.setDictionarieValue(groupId);
				insertParam.setDictionarieType("MessageConsumer");
				insertParam.setDictionarieDescribe("消息消费组id");
				dictionarieService.insertDictionarie(insertParam);
			}
		}
		
	
		QuerySubscribeRelationResponse querySubscribeRelationResponse = querySubscribeRelation();
		if(querySubscribeRelationResponse != null && querySubscribeRelationResponse.getSuccess()) {
			/**存在 */
			updateSubscribeRelation(groupId);
		}else {
			createSubscribeRelation(groupId);
		}
		
		customTopicInit();
	}

	@Override
	public CreateConsumerGroupResponse createConsumerGroup() {

		CreateConsumerGroupResponse response = new CreateConsumerGroupResponse();
		/** 消费组名称 */
		String groupName = aliyunConfig.messageConsumerGroupName;
		 
		if(StringUtils.isNullOrEmpty(groupName)) {
			response.setSuccess(false);
			response.setErrorMessage("消费组名称不能为空");
			return response;
		}
		
		CreateConsumerGroupRequest request = new CreateConsumerGroupRequest(); 
		request.setGroupName(groupName);
		 
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("创建消息组失败");
			logger.error("-----------创建消息组异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("创建消息组失败");
			logger.error("-----------创建消息组异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, "", "", response.getSuccess());
		return response;
	}

	@Override
	public CreateSubscribeRelationResponse createSubscribeRelation(String messageConsumerGroupId) {

		CreateSubscribeRelationResponse response = new CreateSubscribeRelationResponse();
		/** productKey */
		String productKey = aliyunConfig.productKey;
		/** 推送消息类型是否选择设备上报消息 */
		boolean deviceDataFlag = Boolean.valueOf(messageConfig.deviceDataFlag);
		/** 推送消息类型是否选择设备状态变化通知 */
		boolean deviceStatusChangeFlag = Boolean.valueOf(messageConfig.deviceStatusChangeFlag);
		/** 推送消息类型是否选择设备拓扑关系变更 */
		boolean deviceTopoLifeCycleFlag = Boolean.valueOf(messageConfig.deviceTopoLifeCycleFlag);
		/** 推送消息类型是否选择网关子设备发现上报 */
		boolean foundDeviceListFlag = Boolean.valueOf(messageConfig.foundDeviceListFlag);
		/** 推送消息类型是否选择物模型历史数据上报 */
		boolean thingHistoryFlag = Boolean.valueOf(messageConfig.thingHistoryFlag);
		/** 推送消息类型是否选择设备生命周期变更 */	
		boolean deviceLifeCycleFlag = Boolean.valueOf(messageConfig.deviceLifeCycleFlag);
		/** 推送消息类型是否选择OTA升级状态通知 */	
		boolean otaEventFlag = Boolean.valueOf(messageConfig.otaEventFlag);
		/** 推送消息类型是否选择设备标签变更 */	
		boolean deviceTagFlag = Boolean.valueOf(messageConfig.deviceTagFlag);
		/** 推送消息类型是否选择OTA模块版本号上报 */	
		boolean otaVersionFlag = Boolean.valueOf(messageConfig.otaVersionFlag);
		/** 推送消息类型是否选择OTA升级批次状态通知  */	
		boolean otaJobFlag = Boolean.valueOf(messageConfig.otaJobFlag);

		List<String>groupIds = new ArrayList<String>();
		groupIds.add(messageConsumerGroupId);
	 
		CreateSubscribeRelationRequest request = new CreateSubscribeRelationRequest(); 
		request.setDeviceDataFlag(deviceDataFlag);
		request.setDeviceStatusChangeFlag(deviceStatusChangeFlag);
		request.setDeviceTopoLifeCycleFlag(deviceTopoLifeCycleFlag);
		request.setFoundDeviceListFlag(foundDeviceListFlag);
		request.setThingHistoryFlag(thingHistoryFlag);
		request.setDeviceLifeCycleFlag(deviceLifeCycleFlag);
		request.setOtaEventFlag(otaEventFlag);
		request.setDeviceTagFlag(deviceTagFlag);
		request.setOtaVersionFlag(otaVersionFlag);
		request.setOtaJobFlag(otaJobFlag);
		request.setProductKey(productKey);
		request.setType("AMQP");
		request.setConsumerGroupIdss(groupIds);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("创建AMQP服务端订阅失败");
			logger.error("-----------创建AMQP服务端订阅异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("创建AMQP服务端订阅失败");
			logger.error("-----------创建AMQP服务端订阅异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, "", response.getSuccess());
		return response;
	}

	@Override
	public CreateConsumerGroupSubscribeRelationResponse createConsumerGroupSubscribeRelation(
			MessageModel messageModel) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public UpdateConsumerGroupResponse updateConsumerGroup(MessageModel messageModel) {
		UpdateConsumerGroupResponse response = new UpdateConsumerGroupResponse();
		return response;
	}

	@Override
	public DeleteConsumerGroupResponse deleteConsumerGroup(MessageModel messageModel) {
		DeleteConsumerGroupResponse response = new DeleteConsumerGroupResponse();
		/** 消费组名称 */
		String groupId = messageModel.getGroupId();
		 
		if(StringUtils.isNullOrEmpty(groupId)) {
			response.setSuccess(false);
			response.setErrorMessage("消息消费组id不能为空");
			return response;
		}
		
		DeleteConsumerGroupRequest request = new DeleteConsumerGroupRequest(); 
		request.setGroupId(groupId);
		 
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("删除消息消费组失败");
			logger.error("-----------删除消息消费组异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("删除消息消费组失败");
			logger.error("-----------删除消息消费组异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, "", "", response.getSuccess());
		return response;
	}

	@Override
	public QueryConsumerGroupByGroupIdResponse queryConsumerGroupByGroupId(MessageModel messageModel) {
		QueryConsumerGroupByGroupIdResponse response = new QueryConsumerGroupByGroupIdResponse();
		/** 消费组名称 */
		String groupId = messageModel.getGroupId();
		 
		if(StringUtils.isNullOrEmpty(groupId)) {
			response.setSuccess(false);
			response.setErrorMessage("消息消费组id不能为空");
			return response;
		}
		
		QueryConsumerGroupByGroupIdRequest request = new QueryConsumerGroupByGroupIdRequest(); 
		request.setGroupId(groupId);
		 
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询消费组失败");
			logger.error("-----------查询消息消费组异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询消息消费组失败");
			logger.error("-----------查询消息消费组异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, "", "", response.getSuccess());
		return response;
	}

	@Override
	public QuerySubscribeRelationResponse querySubscribeRelation() {
		QuerySubscribeRelationResponse response = new QuerySubscribeRelationResponse();
		String productKey = aliyunConfig.productKey;
		 
		QuerySubscribeRelationRequest request = new QuerySubscribeRelationRequest(); 
		request.setProductKey(productKey);
		request.setType("AMQP");
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询AMQP服务端订阅失败");
			logger.error("-----------查询AMQP服务端订阅异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询AMQP服务端订阅失败");
			logger.error("-----------查询AMQP服务端订阅异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, "", response.getSuccess());
		return response;
	}

	@Override
	public UpdateSubscribeRelationResponse updateSubscribeRelation(String messageConsumerGroupId) {

		UpdateSubscribeRelationResponse response = new UpdateSubscribeRelationResponse();
		/** productKey */
		String productKey = aliyunConfig.productKey;
		/** 推送消息类型是否选择设备上报消息 */
		boolean deviceDataFlag = Boolean.valueOf(messageConfig.deviceDataFlag);
		/** 推送消息类型是否选择设备状态变化通知 */
		boolean deviceStatusChangeFlag = Boolean.valueOf(messageConfig.deviceStatusChangeFlag);
		/** 推送消息类型是否选择设备拓扑关系变更 */
		boolean deviceTopoLifeCycleFlag = Boolean.valueOf(messageConfig.deviceTopoLifeCycleFlag);
		/** 推送消息类型是否选择网关子设备发现上报 */
		boolean foundDeviceListFlag = Boolean.valueOf(messageConfig.foundDeviceListFlag);
		/** 推送消息类型是否选择物模型历史数据上报 */
		boolean thingHistoryFlag = Boolean.valueOf(messageConfig.thingHistoryFlag);
		/** 推送消息类型是否选择设备生命周期变更 */	
		boolean deviceLifeCycleFlag = Boolean.valueOf(messageConfig.deviceLifeCycleFlag);
		/** 推送消息类型是否选择OTA升级状态通知 */	
		boolean otaEventFlag = Boolean.valueOf(messageConfig.otaEventFlag);
		/** 推送消息类型是否选择设备标签变更 */	
		boolean deviceTagFlag = Boolean.valueOf(messageConfig.deviceTagFlag);
		/** 推送消息类型是否选择OTA模块版本号上报 */	
		boolean otaVersionFlag = Boolean.valueOf(messageConfig.otaVersionFlag);
		/** 推送消息类型是否选择OTA升级批次状态通知  */	
		boolean otaJobFlag = Boolean.valueOf(messageConfig.otaJobFlag);
		
		List<String>groupIds = new ArrayList<String>();
		groupIds.add(messageConsumerGroupId);
	 
		UpdateSubscribeRelationRequest request = new UpdateSubscribeRelationRequest(); 
		request.setDeviceDataFlag(deviceDataFlag);
		request.setDeviceStatusChangeFlag(deviceStatusChangeFlag);
		request.setDeviceTopoLifeCycleFlag(deviceTopoLifeCycleFlag);
		request.setFoundDeviceListFlag(foundDeviceListFlag);
		request.setThingHistoryFlag(thingHistoryFlag);
		request.setDeviceLifeCycleFlag(deviceLifeCycleFlag);
		request.setOtaEventFlag(otaEventFlag);
		request.setDeviceTagFlag(deviceTagFlag);
		request.setOtaVersionFlag(otaVersionFlag);
		request.setOtaJobFlag(otaJobFlag);
		request.setProductKey(productKey);
		request.setType("AMQP");
		request.setConsumerGroupIdss(groupIds);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("修改AMQP服务端订阅失败");
			logger.error("-----------修改AMQP服务端订阅异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("修改AMQP服务端订阅失败");
			logger.error("-----------修改AMQP服务端订阅异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, "", response.getSuccess());
		return response;
	}

	@Override
	public QueryProductTopicResponse queryProductTopic() {
		QueryProductTopicResponse response = new QueryProductTopicResponse();
		/** productKey */
		String productKey = aliyunConfig.productKey;
		QueryProductTopicRequest request = new QueryProductTopicRequest(); 
		request.setProductKey(productKey);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询自定义Topic"); 
			logger.error("-----------查询自定义Topic异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询自定义Topic失败");
			logger.error("-----------查询自定义Topic异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, "", response.getSuccess());
		return response;
	}

	@Override
	public CreateProductTopicResponse createProductTopic() {
		CreateProductTopicResponse response = new CreateProductTopicResponse();
		/** productKey */
		String productKey = aliyunConfig.productKey;
		CreateProductTopicRequest request = new CreateProductTopicRequest(); 
		request.setProductKey(productKey);
		request.setOperation("ALL");
		request.setTopicShortName(aliyunConfig.customTopic.replace("/user/", ""));
		request.setDesc("自定义通信topic");
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("建自定义Topic失败");
			logger.error("-----------建自定义Topic异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("建自定义Topic失败");
			logger.error("-----------建自定义Topic异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, "", response.getSuccess());
		return response;
	}

	@Override
	public void customTopicInit() {
		QueryProductTopicResponse queryProductTopicResponse = queryProductTopic();
		boolean flag = false;
		if(queryProductTopicResponse != null && queryProductTopicResponse.getSuccess()) {
			List<ProductTopicInfo> list = queryProductTopicResponse.getData();
			if(list != null && list.size() > 0) {
				for(int i = 0; i < list.size(); i++) {
					ProductTopicInfo info = list.get(i);
					if(info.getTopicShortName().lastIndexOf(aliyunConfig.customTopic) >= 0) {
						flag = true;
						break;
					}
				}
				if(!flag) {
					createProductTopic();
				}
			}
		}
	}

}
